package com.wisdudu.frame.support.util;

import com.orhanobut.logger.Logger;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by qyf on 2016/9/26.
 * 计算工具类
 */

public class ComputeUtil {

    public static int getAgeByBirthday(String birthday) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        Date date = simpleDateFormat.parse(birthday);
        Calendar cal = Calendar.getInstance(Locale.CHINA);
        Calendar currentCal = Calendar.getInstance(Locale.CHINA);
        currentCal.setTime(date);
        if (cal.before(currentCal)) {
//            throw new IllegalArgumentException(
//                    "The birthDay is before Now.It's unbelievable!");
            Logger.e("选择的生日大于当前日期");
            return 0;
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(date);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth)
                    age--;
            } else {
                age--;
            }
        }
        return age;
    }
}
